package cn.bonoon.kernel.web.components;

import static cn.bonoon.kernel.util.StringHelper.isNotEmpty;
import cn.bonoon.kernel.descriptors.UIPropertyAccessor;
import cn.bonoon.kernel.web.html.UIPropertyBuilder;
import cn.bonoon.kernel.web.html.form.ComponentPropertyParser;

public abstract class AbstractInputComponent extends AbstractComponent {

	protected AbstractInputComponent(ComponentPropertyParser componentParser, UIPropertyAccessor accessor) {
		super(componentParser, accessor);

	}

	protected boolean validate;

	/**
	 * 在生成input元素的时候调用
	 * 
	 * @param html
	 * @param builder
	 * @param fieldName
	 */
	protected void initInputAttribute(StringBuilder html, StringBuilder settings, UIPropertyBuilder builder) {
		if (componentParser.isRequired()) {
			validate = true;
			settings.append("required:true");
		}
		String validType = componentParser.getValidType();
		if (isNotEmpty(validType)) {
			if (validate)
				settings.append(", ");
			validate = true;
			settings.append("validType:'").append(validType).append("'");
		}
		String missingMessage = componentParser.getMissingMessage();
		if (isNotEmpty(missingMessage)) {
			if (validate)
				settings.append(", ");
			validate = true;
			settings.append("missingMessage:'").append(missingMessage).append("'");
		}
		String invalidMessage = componentParser.getInvalidMessage();
		if (isNotEmpty(invalidMessage)) {
			if (validate)
				settings.append(", ");
			validate = true;
			settings.append("invalidMessage:'").append(invalidMessage).append("'");
		}
	}

	protected final void input(UIPropertyBuilder builder) {
		int width = componentWidth();
		StringBuilder html = builder.getInitHtml();
		html.append("<input type='text' style='width:").append(width).append("px;'");
		__component(html);
		StringBuilder settings = new StringBuilder();
		initInputAttribute(html, settings, builder);
		if (settings.length() > 0) {
			html.append(" data-settings=\"").append(settings).append("\"");
		}
		html.append("/>");
	}
}
